<template>
  <div class="banner">
    <el-row>
      <el-button type="primary" :disabled="hasChange" @click="saveBanner">
        保存更改
      </el-button>
    </el-row>
    <el-row class="bannerList">
      <el-card
        v-for="(item, index) in list"
        :key="index"
        class="bannerCard"
        :body-style="{ padding: '0px' }"
      >
        <el-image :src="item.imgUrl" :fit="'cover'" />
        <div style="padding: 14px;">
          <el-row>{{ item.title }}</el-row>
          <el-row class="info clearfix">
            <el-col :span="4">
              <span>位置：{{ index + 1 }}</span>
            </el-col>
            <el-col :span="20">
              <BannerEdit
                :index="index"
                :all-banner="list"
                :item="item"
                @changeBanner="changeBanner"
                @deleteBanner="deleteBanner"
              />
            </el-col>
          </el-row>
        </div>
      </el-card>
    </el-row>
  </div>
</template>

<script>
import { getBanner, putBanner } from '@/api/public'
import BannerEdit from '@/components/bannerEdit'
export default {
  name: 'Banner',
  components: { BannerEdit },
  data() {
    return {
      list: [],
      originList: []
    }
  },
  computed: {
    formList() {
      const list = []
      for (let i = 0, len = this.list.length; i < len; i++) {
        list.push(this.list[i].id)
      }
      return list
    },
    hasChange() {
      for (let i = 0, len = this.list.length; i < len; i++) {
        if (this.originList[i] !== this.formList[i]) {
          return false
        }
      }
      return true
    }
  },
  async created() {
    const result = await getBanner()
    this.list = result.data
    for (let i = 0, len = this.list.length; i < len; i++) {
      this.originList.push(this.list[i].id)
    }
  },
  methods: {
    deleteBanner(index) {
      this.list.splice(index, 1)
    },
    changeBanner(index1, index2) {
      const item1 = this.list[index1]
      const item2 = this.list[index2]
      this.list.splice(index1, 1, item2)
      this.list.splice(index2, 1, item1)
      this.$message({
        type: 'success',
        message: '交换成功'
      })
    },
    async saveBanner() {
      const result = await putBanner({
        data: this.formList
      })
      if (result.code === 0) {
        this.$message({
          type: 'success',
          message: '保存成功'
        })
        this.originList = this.formList
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import '~@/styles/mixin.scss';
.banner {
  padding: 20px 40px;
}
.bannerList {
  display: flex;
  flex-wrap: wrap;
}
.info {
  margin-top: 6px;
  // height:30px;
}
.bannerCard {
  margin: 40px;
  width: 400px;
}

.button {
  padding: 0;
  float: right;
}

.el-image {
  height: 200px;
  width: 100%;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: '';
}

.clearfix:after {
  clear: both;
}
</style>
